#include "lvos.h"
#include "thread_intf.h"
#include "log_intf.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

TPool* g_webcliThreadPool = NULL;

void SocketListenCoroutine(void* arg)
{
    (void)arg;
    int listenFd = socket(AF_INET, SOCK_STREAM, 0);
    if (listenFd < 0) {
        LOG_ERROR("Create socket failed");
        return;
    }

    struct sockaddr_in servAddr;
    memset(&servAddr, 0, sizeof(servAddr));
    servAddr.sin_family = AF_INET;
    servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servAddr.sin_port = htons(6789);

    if (bind(listenFd, (struct sockaddr*)&servAddr, sizeof(servAddr)) < 0) {
        LOG_ERROR("Bind socket failed");
        close(listenFd);
        return;
    }

    if (listen(listenFd, 10) < 0) {
        LOG_ERROR("Listen socket failed");
        close(listenFd);
        return;
    }

    LOG_INFO("Socket listening on port 6789");
    while (True) {
        struct sockaddr_in cliAddr;
        socklen_t cliLen = sizeof(cliAddr);
        int connFd = accept(listenFd, (struct sockaddr*)&cliAddr, &cliLen);
        if (connFd < 0) {
            LOG_ERROR("Accept connection failed");
            continue;
        }
        LOG_INFO("New connection from %s:%d", 
                inet_ntoa(cliAddr.sin_addr), ntohs(cliAddr.sin_port));
        close(connFd);
    }
}

void WebcliEventLoopTask(void* arg)
{
    (void)arg;
    LWT_CREATE(SocketListenCoroutine, NULL);
    LwtStartEventLoop();
}

int32_t WebcliInit(void)
{
    if (g_webcliThreadPool != NULL) {
        LOG_ERROR("reinit");
        return RETURN_ERROR;
    }
    int32_t ret = CreatePThreadPool(&g_webcliThreadPool, 1);
    if (ret != RETURN_OK) {
        LOG_ERROR("Create webcli thread pool failed");
        return ret;
    }

    ret = ThreadPoolAddTask(g_webcliThreadPool, WebcliEventLoopTask, NULL);
    if (ret != RETURN_OK) {
        LOG_ERROR("Add webcli event loop task failed");
        ThreadPoolDestroy(g_webcliThreadPool);
        g_webcliThreadPool = NULL;
        return ret;
    }

    LOG_INFO("Webcli module init success");
    return RETURN_OK;
}

void WebcliDeinit(void)
{
    if (g_webcliThreadPool) {
        ThreadPoolDestroy(g_webcliThreadPool);
        g_webcliThreadPool = NULL;
    }
    LOG_INFO("Webcli module deinit success");
    return;
}
